package tr.edu.yildiz.ce.dap.appagent.manager;

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;

import tr.edu.yildiz.ce.dap.appagent.exception.AgentDeploymentException;
import tr.edu.yildiz.ce.dap.appagent.model.App;
import tr.edu.yildiz.ce.dap.appagent.model.AppDefinition;
import tr.edu.yildiz.ce.dap.appagent.model.DapMessage;
import tr.edu.yildiz.ce.dap.appagent.service.DapXmlConverter;
import tr.edu.yildiz.ce.dap.appagent.util.AgentProperties;
import tr.edu.yildiz.ce.dap.appagent.util.DapXmlFilter;

public class ApplicationManager {

	public static void addInstalledApplication(DapMessage dapMessage) throws AgentDeploymentException{
		AppDefinition appDefinition = new AppDefinition();
		App  app = new App();
		app.setName(dapMessage.getAppName());
		app.setVersion(dapMessage.getAppVersion());
		appDefinition.setApp(app);
		appDefinition.setComponentList(dapMessage.getComponentList());
		try {
			String xml = DapXmlConverter.convertToXML(appDefinition);
			File file = new File(getAppFileName(app.getName(),app.getVersion()));
			FileWriter fWriter = new FileWriter(file);
			fWriter.write(xml);
			fWriter.close();
		} catch (Exception e) {
			throw new AgentDeploymentException("Can't save appDefinition of Application");
		}
	}
	
	public static List<AppDefinition> getAllAppDefinition() throws Exception{
		File folder = new File(AgentProperties.getInstance().getBundlePath());
		File[] files = folder.listFiles(new DapXmlFilter());
		List<AppDefinition> appDefinitionList = new ArrayList<AppDefinition>();
		for (File file : files) {
			appDefinitionList.add((AppDefinition) DapXmlConverter.convertToObject(file));
		}
		return appDefinitionList;
	}
	
	public static AppDefinition getAppDefinition(File file) throws Exception{
		return (AppDefinition) DapXmlConverter.convertToObject(file);
	}
	
	public static AppDefinition getAppDefinition(String appName,String appVersion) throws Exception{
		return (AppDefinition) DapXmlConverter.convertToObject(new File(getAppFileName(appName, appVersion)));
	}
	
	public static void removeInstalledApplication(DapMessage dapMessage) {
		File file = new File(getAppFileName(dapMessage.getAppName(), dapMessage.getVersion()));
		if (file.exists())
			file.delete();
	}
	
	private static String getAppFileName(String appName,String appVersion){
		return AgentProperties.getInstance().getBundlePath() + "/" + appName + "-" + appVersion + ".dapxml";
	}
	
	
}
